import 'dart:async';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/widgets/exposure_overlay.dart';

/// 登录视图模型
class LoginViewModel extends BaseViewModel {
  final AuthFocus _authFocus;

  LoginViewModel(this._authFocus);

  bool _isPasswordVisible = false;
  bool get isPasswordVisible => _isPasswordVisible;

  /// 切换密码可见性
  void togglePasswordVisibility() {
    _isPasswordVisible = !_isPasswordVisible;
    notifyListeners();
  }

  /// 使用 Apple 登录
  Future<bool> performLoginWithApple() async {
    try {
      // 显示加载遮罩
      ExposureOverlay.reveal();
      setBusy(true);

      // 获取 Apple 凭证
      final credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

      // 使用 userIdentifier 作为账号（这是 Apple 提供的唯一标识符）
      final userIdentifier = credential.userIdentifier;
      if (userIdentifier == null || userIdentifier.isEmpty) {
        throw Exception('Failed to get Apple user identifier');
      }

      final account = 'apple_$userIdentifier';

      // 检查账号是否已存在
      final accountExists = await _authFocus.isAccountExists(account);

      if (!accountExists) {
        // 账号不存在，注册新用户
        // 生成用户名：优先使用 fullName，否则使用 email，最后使用默认名称
        String username = 'Apple User';
        if (credential.givenName != null || credential.familyName != null) {
          final givenName = credential.givenName ?? '';
          final familyName = credential.familyName ?? '';
          username = '$givenName $familyName'.trim();
          if (username.isEmpty) {
            username = 'Apple User';
          }
        } else if (credential.email != null && credential.email!.isNotEmpty) {
          // 使用 email 的前缀作为用户名
          username = credential.email!.split('@')[0];
        }

        // 使用 userIdentifier 作为密码（实际项目中应该使用更安全的方式）
        final password = userIdentifier;

        // 注册新用户
        await _authFocus.register(
          account: account,
          username: username,
          password: password,
          avatar: 'assets/images/avatar1.png', // Apple 登录不提供头像
        );
      }

      // 登录用户（使用 userIdentifier 作为密码）
      await _authFocus.login(account: account, password: userIdentifier);

      setBusy(false);
      // 隐藏加载遮罩
      ExposureOverlay.conceal();

      FlashNotifier.flashSuccess('Login successful');
      return true;
    } catch (e) {
      setBusy(false);
      // 隐藏加载遮罩
      ExposureOverlay.conceal();

      // 处理用户取消的情况
      if (e.toString().contains('canceled') ||
          e.toString().contains('cancelled')) {
        // 用户取消了登录，不显示错误
        return false;
      }

      final errorMessage = e.toString().replaceAll('Exception: ', '');
      FlashNotifier.flashError('Apple login failed: $errorMessage');
      return false;
    }
  }

  /// 登录
  Future<bool> performLogin({
    required String account,
    required String password,
  }) async {
    try {
      if (account.isEmpty || password.isEmpty) {
        FlashNotifier.flashError('Please fill in all fields');
        return false;
      }

      // 显示加载遮罩
      ExposureOverlay.reveal();
      setBusy(true);

      // 模拟加载两秒
      await Future.delayed(const Duration(seconds: 2));

      await _authFocus.login(account: account, password: password);
      setBusy(false);

      // 隐藏加载遮罩
      ExposureOverlay.conceal();

      FlashNotifier.flashSuccess('Login successful');
      return true;
    } catch (e) {
      setBusy(false);
      // 隐藏加载遮罩
      ExposureOverlay.conceal();
      final errorMessage = e.toString().replaceAll('Exception: ', '');
      FlashNotifier.flashError(errorMessage);
      return false;
    }
  }
}
